package com.study.concurrent.A_ThreadManagement.l_UseThreadFactoryCreateThreads;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ThreadFactory;

/**
 * Created by 赵超 on 2017/3/20.
 */
public class MyThreadFactory implements ThreadFactory {
    /**
     * 用来存储线程对象的数量
     */
    private int counter;
    /**
     * 存放每个线程的名字
     */
    private String name;
    /**
     * 字符串列表，用于存放线程对象的统计数据
     */
    private List<String> stats;

    public MyThreadFactory(String name) {
        counter = 0;
        this.name = name;
        stats = new ArrayList<String>();
    }

    /**
     * 实现newThread方法
     * @param r  Runnable接口
     * @return
     */
    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r, name + "-Thread_" + counter);
        counter++;
        stats.add(String.format("创建线程 %s 名称 %s 创建时间 %s\n",
                thread.getId(), thread.getName(), new Date()));
        return thread;
    }

    public String getStats() {
        StringBuffer buffer = new StringBuffer();
        Iterator<String> it = stats.iterator();
        while (it.hasNext()) {
            buffer.append(it.next()).append("\n");
        }
        return buffer.toString();
    }

}
